package com.sta.oldman.interceptor;

import com.sta.oldman.controller.ExceptionController;
import com.sta.oldman.utils.JWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author: LunBoWang
 * @description: 用户令牌拦截器
 * @date: 2025/7/15 下午4:09
 * @version: 1.0
 */
@Component
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        //1.获取请求路径
        String requestURI = request.getRequestURI();

        //2.判断是否是登录请求
        if (requestURI.contains("/login")||requestURI.contains("/register")||requestURI.contains("/send")) {
            //3.放行
            return true;
        }

        //4.获取token
        String token =request.getHeader("token");

        //5.判断token是否为空
        if(token==null||token.isEmpty()){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //6.校验令牌
        try{
            JWT.parseJWT(token);
        }catch (Exception e){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //7.放行
        return true;
    }
}
